package com.mabeijianxi.jianxiexpression;

import com.mabeijianxi.jianxiexpression.core.ExpressionCache;
import com.mabeijianxi.jianxiexpression.util.PxUtil;
import com.mabeijianxi.jianxiexpression.util.TextUtils;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 显示show
 */
public class ExpressionShowFragment extends ComponentContainer implements TabList.TabSelectedListener {

    private PageSlider pageSlider;
    private TabList.Tab tab1,tab2,tab3;
    private Component mComponent;
    private Context mContext;
    private TabList tabList;
    private List<ComponentContainer> tabComponents = new ArrayList<>();
    private StringBuilder stringBuilder = new StringBuilder();
    ExpressionMainFragment expressionMainFragment;
    ExpressionRecentsFragment expressionRecentsFragment;
    ExpressionSecondFragment expressionSecondFragment;
    private boolean handlerSelect = false;

    /**
     * ExpressionShowFragment
     * @param context
     */
    public ExpressionShowFragment(Context context) {
        super(context);
        mContext = context;
        initView();
    }

    /**
     * ExpressionShowFragment
     * @param context
     * @param attrSet
     */
    public ExpressionShowFragment(Context context, AttrSet attrSet) {
        super(context, attrSet);
        mContext = context;
        initView();
    }

    /**
     * ExpressionShowFragment
     * @param context
     * @param attrSet
     * @param styleName
     */
    public ExpressionShowFragment(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    /**
     * initView
     */
    private void initView() {
        PxUtil.initContext(mContext);
        mComponent = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_main_view,null,false);
        pageSlider = (PageSlider) mComponent.findComponentById(ResourceTable.Id_pagerslider_contain);
        if(pageSlider == null) {
            return;
        }
        expressionMainFragment = new ExpressionMainFragment(mContext);
        expressionSecondFragment = new ExpressionSecondFragment(mContext);
        expressionRecentsFragment = new ExpressionRecentsFragment(mContext);
        tabComponents.add(expressionRecentsFragment);
        tabComponents.add(expressionMainFragment);
        tabComponents.add(expressionSecondFragment);

        PagerAdapter pagerAdapter = new PagerAdapter(mContext,tabComponents);
        pageSlider.setOrientation(Component.HORIZONTAL);
        pageSlider.setSlidingPossible(true);
        pageSlider.setProvider(pagerAdapter);
        pageSlider.setCurrentPage(1);

        tabList = (TabList) mComponent.findComponentById(ResourceTable.Id_tab_chose);
        tabList.setTabLength(185); // 设置Tab的宽度
        tabList.setTabMargin(10); // 设置两个Tab之间的间距
        tab1 = tabList.new Tab(getContext());
        tab1.setText("最近");
        tab1.setTextSize(40);
        tabList.addTab(tab1);
        tab2 = tabList.new Tab(getContext());
        tab2.setText("默认");
        tab2.setTextSize(40);
        tabList.addTab(tab2);
        tab3 = tabList.new Tab(getContext());
        tab3.setText("EMOJI");
        tab3.setTextSize(40);
        tabList.addTab(tab3);
        tab2.select();

        //pageSlider清除缓存
        tabList.addTabSelectedListener(this);
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }

            @Override
            public void onPageChosen(int i) {
                selectFirst(i);
            }
        });
        addComponent(mComponent);
    }

    /**
     * selectFirst
     * @param i
     */
    public void selectFirst(int i){
        handlerSelect = true;
        if(i == 0) {
            tabList.selectTab(tab1);
        }else if(i == 1) {
            tabList.selectTab(tab2);
        } else  {
            tabList.selectTab(tab3);
        }
    }

    @Override
    public void onSelected(TabList.Tab tab) {
        if(tab == tab1) {
            String[][] recents = new String[][]{
                    ExpressionCache.getRecentExpression()
            };
            if (expressionRecentsFragment != null) {
                expressionRecentsFragment.notifyDataNow(recents);
            }
            pageSlider.setCurrentPage(0);

        } else if(tab == tab2) {
            pageSlider.setCurrentPage(1);
            expressionMainFragment.setCurrentPage(handlerSelect);

        } else {
            pageSlider.setCurrentPage(2);
            expressionSecondFragment.setCurrentPage(handlerSelect);
        }
    }

    @Override
    public void onUnselected(TabList.Tab tab) {

    }

    @Override
    public void onReselected(TabList.Tab tab) {

    }

    /**
     * 暂时只支持表情输入
     * */
    public void input (Text textField) {
        expressionMainFragment.setExpressionClickListener(str -> {
            if(str.length() <= 0) {
                return;
            }
            addRecentImage(str);
            stringBuilder.delete(0,stringBuilder.length());
            if(textField.getText() != null) {
                int count = textField.getText().length();
                stringBuilder.append(textField.getText());
            }
            stringBuilder.append(TextUtils.uni2emoji(str));
            textField.setText(stringBuilder.toString());
        });

        expressionRecentsFragment.setExpressionClickListener(str -> {
            if(str.length() <= 0) {
                return;
            }
            addRecentImage(str);
            String[][] recents = new String[][] {
                    ExpressionCache.getRecentExpression()
            };

            if(tabList.getSelectedTab() == tab1) {
                expressionRecentsFragment.notifyDataNow(recents);
            }
            stringBuilder.delete(0,stringBuilder.length());
            if(textField.getText() != null) {
                int count = textField.getText().length();
                stringBuilder.append(textField.getText());
            }
            stringBuilder.append(TextUtils.uni2emoji(str));
            textField.setText(stringBuilder.toString());
        });

        expressionSecondFragment.setExpressionClickListener(str -> {
            if(str.length() <= 0) {
                return;
            }
            addRecentImage(str);
            stringBuilder.delete(0,stringBuilder.length());
            if(textField.getText() != null) {
                int count = textField.getText().length();
                stringBuilder.append(textField.getText());
            }
            stringBuilder.append(TextUtils.uni2emoji(str));
            textField.setText(stringBuilder.toString());
        });

        expressionMainFragment.setExpressionDeleteClickListener(new ExpressionMainFragment.ExpressionDeleteClickListener() {
            @Override
            public void expressionDeleteClick() {
                deleteClick(textField);
            }
        });
        expressionRecentsFragment.setExpressionDeleteClickListener(new ExpressionRecentsFragment.ExpressionDeleteClickListener() {
            @Override
            public void expressionDeleteClick() {
                deleteClick(textField);
            }
        });
        expressionSecondFragment.setExpressionDeleteClickListener(new ExpressionSecondFragment.ExpressionDeleteClickListener() {
            @Override
            public void expressionDeleteClick() {
                deleteClick(textField);
            }
        });
    }

    /**
     * deleteClick
     * @param text
     */
    private void deleteClick(Text text) {
        text.delete(1,true,Text.AUTO_CURSOR_POSITION);
    }

    /**
     * addRecentImage
     * @param str
     */
    private void addRecentImage(String str) {
        int endIndex = getEndIndex();
        for (int i = 0; i < ExpressionCache.getRecentExpression().length; i++) {
//            防止重复
            if(null == ExpressionCache.getRecentExpression()[i]) {
                sort(endIndex,str);
                return;
            }
            if (ExpressionCache.getRecentExpression()[i].equals(str) || i == ExpressionCache.getRecentExpression().length - 1) {
                //                    最多一页);
                sort(i, str);
                return;
            }
        }
        sort(endIndex, str);

    }

    /**
     * sort
     * @param endIndex
     * @param newStr
     */
    private static void sort(int endIndex, String newStr) {
        for (int i = endIndex; i > 0; i--) {
            ExpressionCache.getRecentExpression()[i] = ExpressionCache.getRecentExpression()[i - 1];
        }
        ExpressionCache.getRecentExpression()[0] = newStr;
    }

    /**
     * 得到最后一位有效位
     * @return 最后下标
     */
    private static int getEndIndex() {
        int lastStr = 0;
        String[] strings = ExpressionCache.getRecentExpression();
        for (int i = 0; i < strings.length; i++) {
            if (strings[i] == null || i == strings.length - 1) {
                lastStr = i;
                break;
            }
        }
        return lastStr;
    }
}
